# coding: utf-8

from __future__ import print_function

import os
import config
import logging
import logging.config
import lib.tools.regex as regex
from logging.handlers import RotatingFileHandler

__all__ = ['logger']


class Logger(object):
    NORMAL = ' {0}'
    ERROR = '\033[1;31m {0} \033[0m'
    INFO = '\033[1;32m {0} \033[0m'
    WARN = '\033[1;33m {0} \033[0m'
    DEBUG = '\033[1;34m {0} \033[0m'

    _instance = None

    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(Logger, cls).__new__(cls)
        return cls._instance

    @staticmethod
    def get_instance(window=None):
        if not Logger._instance:
            Logger._instance = Logger(window)
        return Logger._instance

    def initialize(self):
        if not os.path.exists(config.LOG_FOLDER):
            os.mkdir(config.LOG_FOLDER)

    def __init__(self, window=None, name=config.LOG_NAME, console_level=logging.NOTSET, file_level=logging.NOTSET):
        self.initialize()
        self.window = window
        log_formatter = logging.Formatter(fmt=config.LOG_FORMAT, datefmt=config.LOG_DATETIME_FORMAT)
        log_file_name = '{0}{1}'.format(config.LOG_FILE, config.TIMESTAMP)
        file_handler = RotatingFileHandler(log_file_name, maxBytes=1024 * 1024, backupCount=5)
        file_handler.setFormatter(log_formatter)
        file_handler.setLevel(file_level)

        def file_filter(record):
            msg = regex.search_message(record.msg)
            if msg:
                record.msg = msg
            return record
        file_handler.filter = file_filter
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(console_level)
        stream_handler.setFormatter(log_formatter)

        def steam_filter(record):
            self.__window_log(record.msg)
            return record
        stream_handler.filter = steam_filter
        logging.captureWarnings(True)
        self.__logger = logging.getLogger(name)
        self.__logger.propagate = False
        self.__logger.setLevel(logging.INFO)
        self.__logger.addHandler(stream_handler)
        if config.LOG_FILE_ENABLE:
            self.__logger.addHandler(file_handler)

    def __window_log(self, message):
        if self.window:
            new_message = regex.search_message(message)
            if not new_message:
                new_message = message
            self.window.log(new_message)

    def info(self, message=None, color=NORMAL):
        self.__logger.info(color.format(message))

    def debug(self, message=None, color=NORMAL):
        self.__logger.debug(color.format(message))

    def warn(self, message=None, color=NORMAL):
        self.__logger.warning(color.format(message))

    def error(self, message=None, color=ERROR):
        self.__logger.error(color.format(message))

    def log(self, message=None, color=NORMAL):
        print(color.format(message))


